<?php

namespace App\FrontModule\Presenters;

use \Nette\Application\UI\Form, \Nette\Utils\Strings, \Nette\Utils\Image;

/**
 * User presenter
 * @author jirka
 */
class UserPresenter extends BasePresenter {

  /** @var \App\Model\UserManager @inject */
  public $um;
  
  private $userData;
  private $userLevels = array(0 => 'Začátečník', 1 => 'Mírně pokročilý', 2 => 'Pokročilý', 3 => 'Profesionál', 4 => 'Učitel');
  private $userGenders = array(0 => 'Muž', 1 => 'Žena');
  
  /**
   * Default action
   * @param int $userId
   */
  public function actionDetail($userId){
    if(!isset($userId)){
      $this->redirect('Homepage:default');
    }
    
    $this->userData = $this->um->getUserById($userId);
    
    if(!$this->userData){
      $this->redirect('Homepage:default');
    }
    
  }
  
  /**
   * Default render
   * @param int $userId
   */
  public function renderDetail($userId){
    $this->template->userData = $this->userData;
    $this->template->userVideoCommentCount = $this->um->getUsersVideoCommentCount($this->userData);
    $this->template->userVideoViewCount = $this->um->getUsersVideoViewCount($this->userData);
    
    if($this->user->isLoggedIn()){
      $this->template->owner = $this->user->getId() == $this->userData->getId(); 
    }else{
      $this->template->owner = false; 
    }
  }
  
  /**
   * Action for change password
   */
  public function actionChangePassword(){
    if(!$this->user->isLoggedIn()){
      $this->redirect('Homepage:default');
    }
  }
  
  /**
   * Action for change user data
   */
  public function actionChangeUserInfo(){
    if(!$this->user->isLoggedIn()){
      $this->redirect('Homepage:default');
    }
  }
  
  /**
   * Render for change user data
   */
  public function renderChangeUserInfo(){
    $user = $this->um->getUserById($this->user->getId());
    $this->template->userData = $user;
  }
  
  /**
   * Create component password
   * @return \Nette\Application\UI\Form
   */
  public function createComponentChangePasswordForm(){
    $form = new Form();
    
    $form->addPassword('old_password', 'Staré heslo:');
    
    $form->addPassword('password', 'Heslo:')
        ->addRule(Form::FILLED, 'Heslo musí být vyplněno')  
        ->addRule(Form::MAX_LENGTH, 'Heslo může být maximálně 20 znaků dlouhé', 20)
        ->addRule(Form::MIN_LENGTH, 'Heslo musí být minimálně 3 znaky dlouhé', 3);
    
    $form->addPassword('password_again', 'Heslo znovu:')
        ->addRule(Form::EQUAL, 'Nová hesla musí být totožná', $form['password']);
    
    $form->addSubmit('send', 'uložit');
    $form->onSuccess[] = callback($this, 'changePasswordFormSuccess');
    
    return $form;
  }
  
  /**
   * Password form executing
   * @param \Nette\Application\UI\Form $form
   * @return boolean
   */
  public function changePasswordFormSuccess(Form $form){
    if(!$this->user->isLoggedIn()){
      $this->redirect('Homepage:default');
    }
    
    $values = $form->getValues();
    
    $user = $this->um->getUserById($this->user->getId());
    
    if ($user->getPassword() !== \App\Model\UserManager::getHashPassword($values['old_password'], $user->getSalt())) {
			$form->addError('Původní heslo není správné');
      return false;
		}
    
    $this->um->changePassword($user, $values['password']);
    
    $this->flashMessage('Nové heslo byo uloženo', 'success');
    $this->redirect('User:detail', array('userId' => $this->user->getId()));
  }
  
  /**
   * User info form
   * @return \Nette\Application\UI\Form
   */
  public function createComponentChangeUserInfoForm(){
    $form = new Form();
    
    $user = $this->um->getUserById($this->user->getId());
    
    $form->addText('email', 'Email:')
        ->addRule(Form::FILLED, 'Email musí být vyplněn')
        ->addRule(Form::EMAIL, 'Email musí být validní')
        ->addRule(Form::MAX_LENGTH, 'Email je moc dlouhý', 255)
        ->setDefaultValue($user->getEmail());
    
    $form->addUpload('photo', 'Fotka (max 500x500px)')
        ->addCondition(Form::FILLED)
        ->addRule(Form::MAX_FILE_SIZE, 'Obrázek nesmí být větší než 1MB', 1000 * 1024)
        ->addRule(Form::IMAGE, 'Soubor musí být obrázek');
    
    $form->addText('age', 'Věk:')
        ->addCondition(Form::FILLED)
        ->addRule(Form::MIN, 'Věk musí být alespoň 3 roky', 3)
        ->addRule(Form::MAX, 'Věk musí být maximálně 110 let', 110)
        ->addRule(Form::INTEGER, 'Věk musí být celé číslo');
    if($user->getAge() != NULL){
      $form['age']->setDefaultValue($user->getAge());
    }
        
    $form->addText('from', 'Odkud jste:')
        ->addRule(Form::MAX_LENGTH, 'Místo obsahuje příliš mnoho znaků', 255)
        ->setDefaultValue($user->getPlace());
    
    $form->addTextArea('gear', 'Vaše vybavení:')
        ->addRule(Form::MAX_LENGTH, 'Popis kytarového vybavení je moc dlouhý', 255)
        ->setDefaultValue($user->getGear());
    
    $form->addTextArea('about', 'Něco o vás:')
        ->addRule(Form::MAX_LENGTH, 'Text o Vás je moc dlouhý', 255)
        ->setDefaultValue($user->getAbout());
    
    $form->addSelect('level', 'Vaše dovednosti:', $this->userLevels);
    if($user->getLevel() != NULL){
      $form['level']->setDefaultValue(array_search($user->getLevel(), $this->userLevels));
    }
    
    $form->addSelect('gender', 'Jste muž či žena:', $this->userGenders);
    if($user->getGender() != NULL){
      $form['level']->setDefaultValue(array_search($user->getGender(), $this->userGenders));
    }
        
    
    $form->addSubmit('send', 'odeslat');
    $form->onSuccess[] = callback($this, 'changeUserInfoFormSuccess');
    
    return $form;    
  }
  
  /**
   * Executing user info form 
   * @param \Nette\Application\UI\Form $form
   * @return boolean
   */
  public function changeUserInfoFormSuccess(Form $form){
    $values = $form->getValues();
    
    $photo = NULL;
    if ($values['photo']->name != "" && $values['photo']->isImage()) {
      $temp = $values['photo']->getTemporaryFile();
      $size = getimagesize($temp);
      if($size[0] > 500 || $size[1] > 500){
        $form->addError('Maximální rozlišení obrázku je 500px na šířku a 500px na výšku');
        return false;
      }else{
        $photo = $this->savePicture($values['photo']);
      }
		}
    
    $this->um->changeUserInfo($this->user->getId(), $values['email'], $values['age'], $values['from'], $values['gear'], 
        $values['about'], $this->userLevels[$values['level']], $this->userGenders[$values['gender']], $photo);
    
    $this->flashMessage('Změny uloženy', 'success');
    $this->redirect('User:detail', array('userId' => $this->user->getId()));
    
  }
  
  /**
   * Save user photo
   * @param type $picture
   * @return string
   */
  private function savePicture($picture){
    $temp = $picture->getTemporaryFile();
		$image = Image::fromFile($temp);
		$width = $image->getWidth();
    $height = $image->getHeight();
    
    if($width > $height){
      $image->resize(NULL, 200);
    }else if($width < $height){
      $image->resize(200, NULL);
    }else{
      $image->resize(200, 200);
    }
    
    $image->crop(0, 0, 200, 200);

		$hash = Strings::random(10) . time();
		$path = ROOT_DIR . '/content/users/' . $hash;
		mkdir($path);
		$image->save($path . '/image.jpg');

		return $hash;
  }
}
